from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from app.db.session import get_db
from app.core.security import get_current_active_user
from app.crud.sys_config import sys_config
from app.models.user import SysUsers
from app.schemas.sys_config import SysConfig, SysConfigCreate, SysConfigUpdate
from app.utils.response import success_response, error_response, pagination_response
from app.utils.decorators import api_response

router = APIRouter()


@router.get("/sys-configs")
@api_response
async def get_sys_configs(
    *,
    db: Session = Depends(get_db),
    code: str = Query(None, description="配置代码"),
    skip: int = Query(0, description="跳过的记录数"),
    limit: int = Query(100, description="返回的记录数"),
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    获取系统配置列表，支持筛选
    """
    configs = sys_config.search_by_code(db=db, code=code, skip=skip, limit=limit)
    total = sys_config.count_by_code(db=db, code=code)
    
    return pagination_response(data=configs, total=total)


@router.post("/sys-configs")
@api_response
async def create_sys_config(
    *,
    db: Session = Depends(get_db),
    config_in: SysConfigCreate,
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    创建新的系统配置
    """
    try:
        # 检查代码是否已存在
        existing_config = sys_config.get_by_code(db, code=config_in.code)
        if existing_config:
            return error_response(
                code=400,
                message=f"配置代码 '{config_in.code}' 已存在"
            )
        
        config = sys_config.create(db=db, obj_in=config_in, created_by=current_user.user_name)
        return success_response(data=config, message="系统配置创建成功")
        
    except Exception as e:
        return error_response(
            code=500,
            message=f"创建失败: {str(e)}"
        )


@router.get("/sys-configs/{config_id}")
@api_response
async def get_sys_config(
    config_id: int,
    db: Session = Depends(get_db),
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    根据ID获取系统配置
    """
    config = sys_config.get(db=db, id=config_id)
    if not config:
        return error_response(
            code=404,
            message="系统配置未找到"
        )
    return success_response(data=config)


@router.get("/sys-configs/by-code/{code}")
@api_response
async def get_sys_config_by_code(
    code: str,
    db: Session = Depends(get_db),
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    根据代码获取系统配置
    """
    config = sys_config.get_by_code(db=db, code=code)
    if not config:
        return error_response(
            code=404,
            message=f"配置代码 '{code}' 未找到"
        )
    return success_response(data=config)


@router.put("/sys-configs/{config_id}")
@api_response
async def update_sys_config(
    *,
    db: Session = Depends(get_db),
    config_id: int,
    config_in: SysConfigUpdate,
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    更新系统配置
    """
    try:
        config = sys_config.get(db=db, id=config_id)
        if not config:
            return error_response(
                code=404,
                message="系统配置未找到"
            )
        
        # 检查版本号（乐观锁）
        if config.version != config_in.version:
            return error_response(
                code=409,
                message="配置已被其他用户修改，请刷新后重试"
            )
        
        config = sys_config.update(db=db, db_obj=config, obj_in=config_in, updated_by=current_user.user_name)
        return success_response(data=config, message="系统配置更新成功")
        
    except Exception as e:
        return error_response(
            code=500,
            message=f"更新失败: {str(e)}"
        )


@router.delete("/sys-configs/{config_id}")
@api_response
async def delete_sys_config(
    *,
    db: Session = Depends(get_db),
    config_id: int,
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    删除系统配置
    """
    try:
        config = sys_config.get(db=db, id=config_id)
        if not config:
            return error_response(
                code=404,
                message="系统配置未找到"
            )
        
        sys_config.remove(db=db, id=config_id)
        return success_response(message="系统配置删除成功")
        
    except Exception as e:
        return error_response(
            code=500,
            message=f"删除失败: {str(e)}"
        )